package com.lemon.utils;

import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.lemon.constant.Constant;

public class HttpClientUtil {
    public static String doPost(String url, String param, String token) throws Exception {
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            String result = "";
            try {
                HttpPost httpPost = new HttpPost(url);
                httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");
                httpPost.setHeader(Constant.TOKEN_KEY, token);
                httpPost.setEntity(new StringEntity(param,
                        ContentType.create("text/json", "UTF-8")));

                client = HttpClients.createDefault();
                response = client.execute(httpPost);
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    result = EntityUtils.toString(response.getEntity(), "UTF-8");
                } else {
                    result = EntityUtils.toString(response.getEntity(), "UTF-8");
                }
                return result;
            } catch (Exception e) {
                throw e;
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e){
            throw e;
        }
    }
}
